package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"taobao-merchandise/models/mysql"
	"taobao-merchandise/taobaorpc/internal/svc"
	"taobao-merchandise/taobaorpc/taobaorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *taobaorpc.UpdateRequest) (*taobaorpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line

	var product mysql.Product
	mysql.DB.Debug().Where("id = ?", in.Id).Find(&product)
	if product.UserId != in.UserId {
		return nil, fmt.Errorf("权限不足")
	}

	product = mysql.Product{
		Model: gorm.Model{
			ID: uint(in.Id),
		},
		Name:  in.Name,
		Image: in.Image,
		Price: float64(in.Price),
	}
	err := mysql.DB.Debug().Updates(&product)
	if err != nil {
		return nil, fmt.Errorf("更新失败")
	}

	return &taobaorpc.UpdateResponse{Id: int64(product.ID)}, nil
}
